//
//  EnquiryPlanCommitVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/27.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "EnquiryPlanCommitVC.h"
#import "NWEnquiryPlanRequest.h"
#import "DoubleLabCell.h"
#import "orderTotalCell.h"
#import "CargoCell.h"
#import "PlanAgencyModel.h"
#import "CargoChooseVC.h"

#define kUserId   @"user.id"

#define kAgencyId   @"distributor.id"

#define kRemarks   @"remarks"

#define kData       @"data"

#define kDataProductAttributeId  @"productAttributeId"

#define kDataNumber  @"number"


@interface EnquiryPlanCommitVC () <UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource,UITextViewDelegate>

@property (nonatomic,strong) NSMutableArray *dataArr;

@property (nonatomic,strong) NSMutableArray *peopleArr;  //经销商列表  数据

@property (nonatomic,assign) NSInteger week;

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tabView;

@property (nonatomic,strong) NSMutableDictionary*paraDic;   //上传参数 字典

@property (nonatomic,strong) NSMutableArray*paraDataArr;    //上传参数字典中 data对应的value

@property (nonatomic,strong) UITextView *txtView;

@property (nonatomic,strong) UIView *bgView;

@property (nonatomic,assign) NSInteger totalBox;

@property (nonatomic,assign) CGFloat totalPrice;

@end

@implementation EnquiryPlanCommitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self peopleArr];
    [self paraDic];
    [self paraDataArr];
    
    NWEnquiryPlanRequest *request = [[NWEnquiryPlanRequest alloc] init];
    [request startRequestGetAllAgencyWithUserId:[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            _peopleArr = [PlanAgencyModel arrayOfModelsFromDictionaries:result];
            if (_peopleArr.count > 0)
            {
                PlanAgencyModel *model = _peopleArr[0];
                [_paraDic setValue:model.userId forKey:kAgencyId];
            }
            [self setUpUI];
        }
    }];
    
}

- (NSMutableArray *)paraDataArr
{
    if (!_paraDataArr) {
        _paraDataArr = [NSMutableArray array];
    }
    return _paraDataArr;
}

- (NSMutableArray *)peopleArr
{
    if (!_peopleArr) {
        _peopleArr = [NSMutableArray array];
    }
    return _peopleArr;
}

- (NSMutableDictionary *)paraDic
{
    if (!_paraDic)
    {
        _paraDic = [NSMutableDictionary dictionary];
    }
    return _paraDic;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"提交要货计划";
    
    //创建列表
    _tabView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    _tabView.backgroundColor = KwBgColor;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.estimatedRowHeight = 40.0;
    _tabView.rowHeight = UITableViewAutomaticDimension;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    [self.view addSubview:_tabView];
    [_tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];
    
    //创建底部按钮
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmBtn setBackgroundColor:KwBlueColor];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"确认提交" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = KwFont(16.0);
    [confirmBtn addTarget:self action:@selector(startPlaceAnOrder) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 5.0;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-5);
        make.top.equalTo(_tabView.mas_bottom).offset(1);
        make.left.equalTo(@5);
        make.right.equalTo(@-5);
    }];
}


- (void)startPlaceAnOrder
{
    if (_dataArr.count<=0)
    {
        [SVProgressHUD showInfoWithStatus:@"请添加商品"];
    }
    else
    {
        for (int i = 0; i<_dataArr.count; i++)
        {
            ESSInventoryModel *model = _dataArr[i];
            [_paraDataArr addObject:@{kDataProductAttributeId:model.productAttributeId,kDataNumber:model.totalBox}];
        }
        NSString *dataStr = [CommonTool beJsonStrWithObj:_paraDataArr];
        [_paraDic setValue:dataStr forKey:kData];
        [_paraDic setValue:[Singleton shareInstance].userId forKey:kUserId];
        NSMutableArray *allValues = [NSMutableArray arrayWithArray:[_paraDic allValues]];
        if (allValues.count < 4)
        {
            [SVProgressHUD showInfoWithStatus:@"请填写备注信息信息"];
        }
        else
        {
            NWEnquiryPlanRequest *request = [[NWEnquiryPlanRequest alloc] init];
            [request startRequestAddPlanWithDic:_paraDic];
            [request completion:^(id result, NSString *message, id extension, BOOL succ)
            {
                if (succ)
                {
                    [SVProgressHUD showSuccessWithStatus:@"添加计划成功"];
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    [SVProgressHUD showErrorWithStatus:message];
                }
            }];
        }
    }
}

#pragma mark tableViewDelegate,DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 3;
    }
    else if(section == 1)
    {
        if (_dataArr &&_dataArr.count>0)
        {
            return _dataArr.count+2;
        }
        else
        {
            return 2;
        }
    }
    else
    {
        return 1;
    }
}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 30;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *headView = [UIView new];
//    UILabel *lab = [UILabel new];
//    lab.text = @"营养多";
//    lab.textAlignment = NSTextAlignmentLeft;
//    lab.font = KwFont(14);
//    lab.textColor = KwBgColor;
//    [headView addSubview:lab];
//    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(@20);
//        make.top.equalTo(@10);
//        make.bottom.equalTo(@-10);
//    }];
//    return headView;
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *doubleCell_id = @"DoubleLabCell";
    if (indexPath.section == 0)
    {
        DoubleLabCell *cell = [tableView dequeueReusableCellWithIdentifier:doubleCell_id];
        if (!cell)
        {
            cell = [[DoubleLabCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:doubleCell_id];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (indexPath.row == 0)
        {
            cell.constStr = @"经销商";
            if (_peopleArr && _peopleArr.count > 0)
            {
                PlanAgencyModel*model = _peopleArr[0];
                NSString *nameStr  = model.userName;
                cell.paraStr = nameStr;
            }
            
        }
        else if (indexPath.row == 1)
        {
            cell.constStr = @"日期";
            
            NSDate * senddate=[NSDate date];
            NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"HH:mm"];
//            NSString * locationString=[dateformatter stringFromDate:senddate];

            NSCalendar * cal=[NSCalendar currentCalendar];
            NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
            NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
            NSInteger year=[conponent year];
            NSInteger month=[conponent month];
            NSInteger day=[conponent day];
            float a = day/7;
            if (a<=1)
            {
                _week = 1;
            }
            else
            {
                _week = ceil(a+1);
            }
            
            NSString * nsDateString= [NSString stringWithFormat:@"%zd-%zd",year,month];
            
            cell.paraStr = nsDateString;
            
        }
        else
        {
            cell.constStr = @"第几周";
            cell.paraStr = [NSString stringWithFormat:@"第%zd周",_week];
        }
        return cell;
    }
    else if (indexPath.section == 1)
    {
        
        if (indexPath.row == 0)
        {
            UITableViewCell *cell;
            //这一行为 酷我商城
            cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell_Id"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell_Id"];
                [self createCellUIWithCell:cell];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        else
        {
            if (_dataArr &&_dataArr.count>0)
            {
                if(indexPath.row == _dataArr.count+1)
                {
                    orderTotalCell *cell;
                    //这一行为合计
                    cell = [tableView dequeueReusableCellWithIdentifier:@"orderTotalCell"];
                    if (!cell)
                    {
                        cell = [[orderTotalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"orderTotalCell"];
                    }
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    cell.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",_totalPrice];
                    cell.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)_totalBox];
                    return cell;
                }
                else
                {
                    CargoCell *cell;
                    //其余为商品展示
                    cell = [tableView dequeueReusableCellWithIdentifier:@"CargoCell"];
                    if (!cell)
                    {
                        cell = [[CargoCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CargoCell"];
                    }
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    if (_dataArr && _dataArr.count>0)
                    {
                        ESSInventoryModel *model = _dataArr[indexPath.row-1];
                        cell.model = model;
                    }
                    return cell;
                }
            }
            else
            {
                UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell3"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell3"];
                    UIImageView *img = [UIImageView new];
                    img.image = kImg(@"nodata");
                    [cell addSubview:img];
                    __weak UITableViewCell *weakCell  = cell;
                    [img mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.centerX.equalTo(weakCell.mas_centerX);
                        make.top.equalTo(weakCell.mas_top).offset(30);
                        make.bottom.equalTo(weakCell.mas_bottom).offset(-30);
                        make.size.mas_equalTo(CGSizeMake(150, 120));
                    }];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }
    }
    else
    {
        UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell2"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell2"];
            _txtView = [[UITextView alloc] init];
            _txtView.delegate = self;
            _txtView.text = @"备注";
            _txtView.font = KwFont(15);
            _txtView.backgroundColor = KwGaryColor;
            [cell addSubview:_txtView];
            __weak UITableViewCell *weakCell  = cell;
            [_txtView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(weakCell.mas_left).offset(20);
                make.right.equalTo(weakCell.mas_right).offset(-20);
                make.top.equalTo(weakCell.mas_top).offset(20);
                make.height.equalTo(@70);
                make.bottom.equalTo(weakCell.mas_bottom).offset(-20);
                
            }];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

//创建第一行酷我商城单元格
- (void)createCellUIWithCell:(UITableViewCell *)cell
{
    UIImageView *img = [UIImageView new];
    img.image = kImg(@"shangchen");
    [cell addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@15);
        make.top.equalTo(@10);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    
    UILabel *lab = [UILabel new];
    lab.text = @"酷我商城";
    lab.font = KwFont(14.0);
    [cell addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(img.mas_right).offset(10);
        make.height.equalTo(@14);
        make.top.equalTo(img.mas_top);
    }];
    
    UIImageView *img2 = [UIImageView new];
    img2.image = kImg(@"next");
    [cell addSubview:img2];
    [img2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-15);
        make.size.mas_equalTo(CGSizeMake(12, 15));
        make.top.equalTo(img.mas_top);
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = KwGaryColor;
    [cell addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(img.mas_bottom).offset(10);
        make.left.right.equalTo(@0);
        make.height.equalTo(@1.5);
        make.bottom.equalTo(@0);
    }];
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            //展示经销商
            
            _bgView = [UIView new];
            _bgView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.7];
            [self.view addSubview:_bgView];
            [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.bottom.equalTo(@0);
            }];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissView)];
            [_bgView addGestureRecognizer:tap];
            
            UIPickerView *pickView = [[UIPickerView alloc] init];
            pickView.backgroundColor = [UIColor whiteColor];
            pickView.showsSelectionIndicator=YES;
            pickView.dataSource = self;
            pickView.delegate = self;
            [_bgView addSubview:pickView];
            [pickView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(_bgView);
                make.height.equalTo(@200);
            }];
        }
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0)
        {
            //进入酷我商城
            CargoChooseVC *vc  = [[CargoChooseVC alloc] init];
            vc.type = CargoVCTypeEnquiryPlan;
            vc.block = ^(NSMutableArray *dataArr)
            {
                _dataArr = dataArr;
                NSInteger aTotalBox = 0;
                CGFloat aTotalPrice = 0;
                for (int i = 0; i<_dataArr.count; i++)
                {
                    ESSInventoryModel *model = _dataArr[i];
                    aTotalBox = aTotalBox + [model.totalBox integerValue];
                    aTotalPrice = aTotalPrice + [model.price floatValue]*[model.totalBox integerValue];
                }
                _totalBox = aTotalBox;
                _totalPrice=aTotalPrice;
                NSIndexSet *sec = [NSIndexSet indexSetWithIndex:1];
                [_tabView reloadSections:sec withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)dismissView
{
    [_bgView removeFromSuperview];
    
}

#pragma Mark -- UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// pickerView 每列个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return _peopleArr.count;
}

#pragma Mark -- UIPickerViewDelegate
// 每列宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return 180;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    PlanAgencyModel*model = _peopleArr[row];
    NSString *nameStr  = model.userName;
    return nameStr;
}

// 返回选中的行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    DoubleLabCell *cell = [_tabView cellForRowAtIndexPath:index];
    PlanAgencyModel*model = _peopleArr[row];
    NSString *nameStr  = model.userName;
    cell.paraStr = nameStr;
    [_paraDic setObject:model.userId forKey:kAgencyId];
}

#pragma  mark textviewDelegate

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [_paraDic setObject:_txtView.text forKey:kRemarks];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
